import {Injectable} from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import {Observable} from 'rxjs';
import {CommonParams} from '../utils/common-params';
import {environment} from '../environments/environment';
import {Response} from './response';

@Injectable({
  providedIn: 'root'
})
export class RequestService {
  private backend = environment.apiHost;

  static buildHttpParam(params: any): HttpParams {
    if (!params) {
      return null;
    }
    let httpParams = new HttpParams();
    for (const key of Object.keys(params)) {
      if (params[key] != null && params[key] !== undefined) {
        httpParams = httpParams.append(key, params[key]);
      }
    }
    return httpParams;
  }

  static transformRequest(data) {
    let str = '';
    for (const i in data) {
      if (data.hasOwnProperty(i) && data[i] != null && data[i] !== undefined) {
        str += i + '=' + data[i] + '&';
      }
    }
    return str.substring(0, str.length - 1);
  }

  constructor(private http: HttpClient) {
  }

  get(url: string, params?: Response): Observable<Response> {
    return this.http.get<Response>(url, {
      params: RequestService.buildHttpParam(params), headers: new HttpHeaders({
        'Content-Type': 'application/json;charset=UTF-8'
      })
    }).map(d => new Response(d));
  }

  post(url: string, params?: any): Observable<Response> {
    return this.http.post<Response>(url, params, {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    }).map(d => new Response(d));
  }

  download(url: string, params?: any) {
    return this.http.get(url, {
      params: RequestService.buildHttpParam(params),
      headers: new HttpHeaders({
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }),
      responseType: 'blob'
    });

  }
}
